package com.tiance.demo.service.mysql.utils;

public class ByteUtils {

    /**
     * Byte数组转十六进制字符串
     *
     * @param b
     * @return
     */
    public static String bytes2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }

    public static int bytes2Int(byte[] byteNum) {
        byte[] bytes = new byte[4];
        if (byteNum.length < 4) {
            System.arraycopy(byteNum, 0, bytes, 4 - byteNum.length, byteNum.length);
        } else {
            bytes = byteNum;
        }

        int num = 0;
        for (int i = 0; i < 4; ++i) {
            num <<= 8;
            num |= (bytes[i] & 0xff);
        }
        return num;
    }

    public static long bytes2Long(byte[] byteNum) {
        long num = 0;
        for (int i = 0; i < 8; ++i) {
            num <<= 8;
            num |= (byteNum[i] & 0xff);
        }
        return num;
    }

    /**
     * 16进制转换成为string类型字符串
     */
    public static String bytesToASCIIStr(byte[] bytes) {
        return new String(bytes);
    }

    public static byte[] hexStr2Bytes(String hexStr) {
        if (hexStr == null || hexStr.equals("")) {
            return null;
        }
        hexStr = hexStr.replaceAll("\\s", "");
        hexStr = hexStr.toUpperCase();
        int length = hexStr.length() / 2;
        char[] hexChars = hexStr.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    public static int hexStr2Int(String hexStr) {
        return bytes2Int(hexStr2Bytes(hexStr));
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static void main(String[] args) {
        byte[] bytes = hexStr2Bytes("000010002E");
        System.out.println();
    }
}
